<?php

/**
 * Device Image handler class
 *
 * This class converts, scales, resizes and stores images
 */

class DeviceImage {
	private $name, $tmp_name, $type, $size, $error;
	private $img;

	function __construct( $file ) {
		$this->tmp_name = $file['tmp_name'];
		$this->type = $file['type'];
		$this->name = $file['name'];
		$this->size = $file['size'];
		$this->error = $file['error'];
		//Init image object
		$this->loadImage();
	}
	
	function loadImage() {
		switch( $this->getType() ) {
			case 'image/png':
				$this->img = @imagecreatefrompng( $this->getTempPath() );
				break;
			case 'image/jpeg':
				$this->img = @imagecreatefromjpeg( $this->getTempPath() );
				break;
		}
	}
	
	function __destruct() {
		//Clean up the memory
		if ( $this->img ) {
			imagedestroy( $this->img );
		}
	}
	
	public function getError() {
		return $this->error;
	}
	
	public function getName() {
		return $this->name;
	}
	
	public function getTempPath() {
		return $this->tmp_name;
	}
	
	public function getType() {
		return $this->type;
	}
	
	public function getSize() {
		return $this->size;
	}
	
	public function getWidth() {
		return imagesx( $this->img );
	}
	
	public function getHeight() {
		return imagesy( $this->img );
	}
	
	public function resize( $new_height = 1280 ) {
		if ( $this->getHeight() > $new_height ) {
			$ratio = $this->getWidth() / $this->getHeight();
			$new_width = $ratio * $new_height;
			$new_image = imagecreatetruecolor($new_width, $new_height);
			imagecopyresampled($new_image, $this->img, 0, 0, 0, 0, $new_width, $new_height, $this->getWidth(), $this->getHeight());
			$this->img = $new_image;
		}
	}
	
	public function save() {
		$filename = $this->generateFilename();
		switch( $this->getType() ) {
			case 'image/png':
				$saved = imagepng( $this->img, 'uploads/'.$filename );
				break;
			case 'image/jpeg':
				$saved = imagejpeg( $this->img, 'uploads/'.$filename );
				break;
		}
		if ( $saved ) {
			return $filename;
		}
		return false;
	}
	
	public function generateFilename() {
		$filename = md5(time());
		switch( $this->getType() ) {
			case 'image/png':
				$filename .= '.png';
				break;
			case 'image/jpeg':
				$filename .= '.jpg';
				break;
		}
		return $filename;
	}
}

?>